<script setup>
import { getCurrentInstance, reactive, ref } from 'vue';
import { ElForm } from 'element-plus'
import { useRouter } from 'vue-router';
import { useUserStore, useTokenStore } from '../stores'

const { proxy } = getCurrentInstance()
const router = useRouter()

const userInfo = useUserStore()
const tokenInfo = useTokenStore()

const emailRegex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
const phoneRegex = /^[1][3,4,5,7,8][0-9]{9}$/

const accountFormRef = ref()

const accountInfo = reactive({
    account: "",
    secret: "",
    confirm: "",
    isExists: true,
})

const checkUserExists = () => {
    proxy.$http.get(`/api/users/${accountInfo.account}`)
        .then(res => {
            accountInfo.isExists = true
        })
        .catch(err => {
            if (err.response) {
                if (err.response.status === 404) {
                    accountInfo.isExists = false
                } else {
                    console.log(err)
                }
            } else {
                console.log(err)
            }
        })
}

const userLogin = () => {
    proxy.$http.post('/api/auth/login', { account: accountInfo.account, secret: accountInfo.secret })
        .then(res => {
            if (res.data) {
                // update user info
                userInfo.id = res.data.user.id
                userInfo.name = res.data.user.name
                userInfo.email = res.data.user.email
                userInfo.phone = res.data.user.phone
                userInfo.roles = res.data.user.roles
                userInfo.avatar = res.data.user.avatarUrl

                // update token info
                tokenInfo.id = res.data.user.id
                tokenInfo.token = res.data.accessToken
                tokenInfo.ticket = res.data.ticket

                router.push("/")
            }
        })
        .catch(err => console.log(err))
}

const validateAccount = (rule, value, callback) => {
    if (value === '') {
        return callback(new Error('请输入邮箱或手机号'))
    }
    setTimeout(() => {
        if (!accountInfo.account.match(emailRegex) && !accountInfo.account.match(phoneRegex)) {
            callback(new Error("请检查账号格式"))
        } else {
            callback()
        }
    }, 1000)
}

const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error("请输入密码"))
    } else if (!accountInfo.isExists) {
        if (accountInfo.checkPass !== '') {
            if (!accountFormRef.value) return
            accountFormRef.value.validateField('confirm', () => null)
        }
        callback()
    } else {
        callback()
    }
}

const validateConfirm = (rule, value, callback) => {
    if (value === '') {
        callback(new Error("请再次输入密码"))
    } else if (value !== accountInfo.secret) {
        callback(new Error("两次输入不一致"))
    } else {
        callback()
    }
}

const rules = reactive({
    account: [{ validator: validateAccount, trigger: 'blur' }],
    secret: [{ validator: validatePass, trigger: 'blur' }],
    confirm: [{ validator: validateConfirm, trigger: 'blur' }]
})

const onSubmit = formEl => {
    if (!formEl) return
    formEl.validate(valid => {
        if (valid) {
            if (accountInfo.isExists) {
                userLogin()
            } else {
                // register
                proxy.$http.post("/api/users/register", { account: accountInfo.account, secret: accountInfo.secret })
                    .then()
                    .catch(err => console.log(err))
                userLogin()
            }
        } else {
            return false
        }
    })
}
</script>

<template>
    <div class="login-container">
        <el-form
            ref="accountFormRef"
            :model="accountInfo"
            label-width="120px"
            status-icon
            :rules="rules"
        >
            <!-- 账号 -->
            <el-form-item label="账号" prop="account">
                <el-input
                    v-model="accountInfo.account"
                    clearable
                    autocomplete="off"
                    placeholder="邮箱/手机号"
                    @change="checkUserExists"
                ></el-input>
            </el-form-item>

            <!-- 密码 -->
            <el-form-item label="密码" prop="secret">
                <el-input
                    v-model="accountInfo.secret"
                    type="password"
                    show-password
                    clearable
                    placeholder="密码"
                ></el-input>
            </el-form-item>

            <!-- 确认密码 -->
            <el-form-item v-if="!accountInfo.isExists" label="确认密码" prop="confirm">
                <el-input
                    v-model="accountInfo.confirm"
                    type="password"
                    show-password
                    clearable
                    placeholder="确认密码"
                ></el-input>
            </el-form-item>

            <!-- 确认登陆 -->
            <el-form-item>
                <el-button
                    type="primary"
                    @click="onSubmit(accountFormRef)"
                >{{ accountInfo.isExists ? "登录" : "注册" }}</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<style>
.login-container .el-form .el-form-item {
    margin: 10px;
    padding: 10px;
}

.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    width: 400px;
    height: 300px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border: 2px solid black;
}
</style>